package com.tianlang.security;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

import com.jfinal.plugin.activerecord.Record;

/**
 * 
 * @author mcp
 *
 */
public class AuthorizeFilter extends AuthorizationFilter {
	private static final Logger log = Logger.getLogger(AuthorizeFilter.class);

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		log.info("----------isAccessAllowed方法被调用----------");
		// -----------------用户验证------------------
		Subject currentUser = getSubject(request, response);
		// 如果还未认证
		if (!currentUser.isAuthenticated()) {
			return false;
		}
		Record user = (Record) currentUser.getPrincipal();
		if (user == null) {
			return false;
		}
		if (user.getStr("username").equals("superadmin")) {
			// 超级管理员具有所有权限
			return true;
		}
		// -----------------获取资源权限表达式-------------
		// request中加入attribute便于controller调用admin的信息
		request.setAttribute("user", user);
		// 根据actionKey分析出权限表达式
		HttpServletRequest hsr = ((HttpServletRequest) request);
		String root = hsr.getContextPath();
		String url = hsr.getRequestURI();
		String actionKey = url.replace(root, "");
		if ("".equals(actionKey)) {
			actionKey = "/";
		}
		// -----------------进行鉴权-------------
		if (currentUser.isPermitted(actionKey)) {
			// 鉴权
			return true;
		} else {
			return false;
		}
	}

}
